/*
 *    Copyright (c) 2018-2025, proj All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the proj developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: proj
 */

package com.ykht.proj.activity.controller.b;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ykht.proj.activity.constant.CardConstant;
import com.ykht.proj.activity.entity.*;
import com.ykht.proj.activity.service.VConsumeRecordService;
import com.ykht.proj.activity.service.VDiscountPlanService;
import com.ykht.proj.activity.service.VOrderCardShopService;
import com.ykht.proj.activity.vo.CardShopDto;
import com.ykht.proj.activity.vo.CnGroupShopVoReq;
import com.ykht.proj.activity.vo.VConsumeRecordVo;
import com.ykht.proj.activity.vo.VInfoVo;
import com.ykht.proj.admin.api.entity.SysUser;
import com.ykht.proj.admin.api.feign.RemoteUserService;
import com.ykht.proj.admin.api.vo.UserVO;
import com.ykht.proj.common.core.util.R;
import com.ykht.proj.common.log.annotation.SysLog;
import com.ykht.proj.common.security.util.SecurityUtils;
import com.ykht.proj.coupon.Enum.UserTypeEnum;
import com.ykht.proj.coupon.api.feign.RemoteShopService;
import com.ykht.proj.coupon.api.feign.RemoteWaiterExtService;
import com.ykht.proj.coupon.entity.CnShop;
import com.ykht.proj.coupon.entity.FxWaiterExt;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 核销表（消费记录表） B端
 *
 * @author csg
 * @date 2021-05-21 14:21:47
 */
@RestController
@AllArgsConstructor
@RequestMapping("b/vconsumerecord" )
@Api(value = "vconsumerecord", tags = "B端 核销表（消费记录表）管理")
@Slf4j
public class BConsumeRecordController {

	private final RemoteUserService remoteUserService;
	private final RemoteWaiterExtService remoteWaiterExtService;
    private final VConsumeRecordService vConsumeRecordService;
	private final VOrderCardShopService vOrderCardShopService;
	private final RemoteShopService remoteShopService;


    /**
     * B端 卡核销记录 分页查询
     * @param page 分页对象
     * @param vConsumeRecordVo 核销表（消费记录表）
     * @return
     */
    @ApiOperation(value = "B端 卡核销记录 分页查询", notes = "B端 卡核销记录 分页查询")
    @GetMapping("/getBConsumeRecordPage" )
    public R getBConsumeRecordPage(Page page, VConsumeRecordVo vConsumeRecordVo) {
		log.info("->B端 卡核销记录 分页查询{}{}", page, vConsumeRecordVo);
		Integer userType = SecurityUtils.getUser().getUserType();
		if (UserTypeEnum.WAITER.getValue().equals(userType)){
			FxWaiterExt userExt = remoteWaiterExtService.getUserExt();
			vConsumeRecordVo.setWaiterId(userExt.getId());
		} else {
			vConsumeRecordVo.setSjId(SecurityUtils.getSjId());
			vConsumeRecordVo.setLoginRoleType(userType);
		}
		IPage<VConsumeRecordVo> iPage = vConsumeRecordService.getBConsumeRecordPage(page, vConsumeRecordVo);
		if (null != iPage.getRecords() && iPage.getRecords().size() > 0){
			List<VConsumeRecordVo> recordVoList = iPage.getRecords();
			List<Long> longList = recordVoList.stream().map(VConsumeRecordVo::getLoginId).collect(Collectors.toList());
			List<SysUser> userList = remoteUserService.userByIds(longList);
			recordVoList.stream().forEach(itme -> {
				userList.stream().forEach(user -> {
					if (itme.getLoginId().equals(Long.valueOf(user.getUserId()))) {
						itme.setUsername(user.getUsername());
						itme.setNickName(user.getNickName());
						itme.setUserPhone(user.getPhone());
					}
				});
			});
			iPage.setRecords(recordVoList);
		}
        return R.ok(iPage);
    }


	/**
	 * B端  根据核销ID获取记录详情
	 * @param id 核销ID
	 * @return
	 */
	@ApiOperation(value = "B端 根据核销ID获取记录详情", notes = "B端 根据核销ID获取记录详情")
	@GetMapping("/getByIdConsumeRecord" )
	public R getByIdConsumeRecord(Long id) {
		log.info("->B端 根据核销ID获取记录详情{}", id);
		VConsumeRecordVo consumeRecordVo = vConsumeRecordService.getByIdConsumeRecord(id);
		UserVO byIdUser = remoteUserService.getByIdUser(consumeRecordVo.getLoginId());
		consumeRecordVo.setUsername(byIdUser.getUsername());
		consumeRecordVo.setNickName(byIdUser.getNickName());
		consumeRecordVo.setUserPhone(byIdUser.getPhone());
		return R.ok(consumeRecordVo);
	}

	/**
	 * B端  根据核销码获取记录详情
	 * @param useCode 核销ID
	 * @return
	 */
	@ApiOperation(value = "B端 根据核销码获取记录详情", notes = "B端 根据核销码获取记录详情")
	@GetMapping("/getByUseCodeConsumeRecord" )
	public R<VConsumeRecordVo> getByUseCodeConsumeRecord(String useCode) {
		log.info("->B端 根据核销码获取记录详情{}", useCode);
		VConsumeRecordVo vConsumeRecordVo = new VConsumeRecordVo();
		VInfo info = new VInfo().selectOne(Wrappers.lambdaQuery(VInfo.class).eq(VInfo::getUseCode, useCode));
		VCard card = new VCard().selectById(info.getCardId());
		vConsumeRecordVo.setCreateTime(LocalDateTime.now());
		vConsumeRecordVo.setUseCode(useCode);
		vConsumeRecordVo.setCardName(card.getName());
		vConsumeRecordVo.setStartTime(info.getStartTime());
		vConsumeRecordVo.setEndTime(info.getEndTime());
		vConsumeRecordVo.setInfoStatus(info.getStatus().toString());
		vConsumeRecordVo.setPurchaseRemind(card.getPurchaseRemind());
		R<Integer> countShop = vOrderCardShopService.getByInfoIdCountShop(info.getId(),
				card.getPriceType().equals(CardConstant.CARD_PRICE_TYPE_2) ? null : card.getPriceType());
		Integer userType = SecurityUtils.getUser().getUserType();
		Long shopId = null;
		UserVO user = remoteUserService.getByIdUser(SecurityUtils.getUserId());
		if (UserTypeEnum.WAITER.getValue().equals(userType)){
			FxWaiterExt userExt = remoteWaiterExtService.getUserExt();
			if (null == userExt){
				return R.failed("当前账号没有绑定的门店");
			}
			vConsumeRecordVo.setWaiterId(userExt.getId());
			vConsumeRecordVo.setUseName(user.getNickName());
			shopId = userExt.getShopId();
		} else {
			CnShop shop = remoteShopService.getByLoginIdShop();
			if (null == shop) {
				return R.failed("当前账号没有绑定的门店");
			}
			vConsumeRecordVo.setUseName(shop.getName());
		}
		vConsumeRecordVo.setShopCount(countShop.getCode());
		return R.ok(vConsumeRecordVo);
	}




	/**
	 * 验证 订单是否合格(卡是否可以使用)
	 *
	 * @param vConsumeRecordVo
	 * @return
	 */
	@ApiOperation(value = "验证 订单是否合格(卡是否可以使用)")
	@SysLog("验证 订单是否合格(卡是否可以使用)")
	@PostMapping("verificationOrder")
	public R verificationOrder(@RequestBody VConsumeRecordVo vConsumeRecordVo) {
		log.info("->验证 订单是否合格(卡是否可以使用)", JSONUtil.toJsonStr(vConsumeRecordVo));
		return vConsumeRecordService.verificationOrder(vConsumeRecordVo);
	}

	/**
	 * 新增核销表（消费记录表）
	 * @param vConsumeRecordVo 核销表（消费记录表）
	 * @return R
	 */
	@ApiOperation(value = "新增核销表（消费记录表）", notes = "新增核销表（消费记录表）")
	@SysLog("新增核销表（消费记录表）" )
	@PostMapping("addVConsumeRecord")
	public R addVConsumeRecord(@RequestBody VConsumeRecordVo vConsumeRecordVo) {
		log.info("->新增核销表（消费记录表）", JSONUtil.toJsonStr(vConsumeRecordVo));
		return vConsumeRecordService.addVConsumeRecord(vConsumeRecordVo);
	}



}
